import {Component, ViewEncapsulation, OnInit} from '@angular/core';
import {FormGroup, AbstractControl, FormBuilder, Validators} from '@angular/forms';
import {Router} from "@angular/router";
import {Http, RequestOptions, Headers, Response} from "@angular/http";
import {JwtHelper} from "angular2-jwt";
import {Base64} from "../common/base64";
import {ServerUrl} from "../common/serverurl";

@Component({
  selector: 'login',
  encapsulation: ViewEncapsulation.None,
  styleUrls: ['./login.scss'],
  templateUrl: './login.html',
})
export class Login implements OnInit{

  public form:FormGroup;
  public username:AbstractControl;
  public password:AbstractControl;
  public submitted:boolean = false;
  public jwtHelper: JwtHelper = new JwtHelper();
  public failure:boolean;
  public message:string;
  public iflogin:boolean;
  constructor(private router:Router,fb:FormBuilder,private http:Http) {
    this.form = fb.group({
      'username': ['', Validators.compose([Validators.required])],
      'password': ['', Validators.compose([Validators.required])]
    });

    this.username = this.form.controls['username'];
    this.password = this.form.controls['password'];
    this.failure=false;
    this.message=null;
    this.iflogin=false;
  }
  ngOnInit(){
    if(localStorage.getItem('token') !== null){
      if(!this.jwtHelper.isTokenExpired(localStorage.getItem('token'))){
        this.router.navigate(['pages/vuls/vullist']);
      }
    }
  }

  public onSubmit(values:Object):void {
    this.submitted = true;
    this.iflogin=true;
    if (this.form.valid) {
      let options: RequestOptions = new RequestOptions({
        headers: new Headers({ 'Content-Type': 'application/json' })
      });
      let username=new Base64().encode(values['username']);
      let password=new Base64().encode(values['password']);
      let a={name:username,password:password};
      this.http.post(ServerUrl+'login/byname',a,options).map((response: Response) => response.json()).subscribe(
        data=>{
          if(data.message=='mis match'){
            this.failure=true;
            this.message=data.message;
            this.iflogin=false;
          }else if(data.message=='refused'){
            this.failure=true;
            this.message=data.message;
            this.iflogin=false;
          }else{
            let token :string=data.token;
            localStorage.setItem('token',token);
            console.log(token);
            console.log(
              `expiration: ${this.jwtHelper.getTokenExpirationDate(token)};`,
              `is expired: ${this.jwtHelper.isTokenExpired(token)};`,
              `decoded: ${JSON.stringify(this.jwtHelper.decodeToken(token))}`
            );
            this.router.navigate(['pages/vuls/vullist']);
          }
        },error=>{console.log(error);this.iflogin=false;});
    }
  }
}
